package com.gitee.ly.reentranlock;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

@Slf4j
public class ServiceNameReenTranLock {
    private static final Map<String, ReentrantLock> serviceNameReenTranLock = new HashMap<>();

    public static <T> T lockAndUnLock(String serviceName, Supplier<T> supplier, long timeoutSeconds) {
        ReentrantLock serviceNameReentrantLock = serviceNameReenTranLock.putIfAbsent(serviceName, new ReentrantLock(true));
        serviceNameReentrantLock = serviceNameReentrantLock != null ? serviceNameReentrantLock : serviceNameReenTranLock.get(serviceName);
        try {
            boolean lock = serviceNameReentrantLock.tryLock(timeoutSeconds, TimeUnit.SECONDS);
            if (lock) {
                try {
                    return supplier.get();
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex);
                    throw ex;
                } finally {
                    serviceNameReentrantLock.unlock();
                }
            } else {
                return null;
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }
    }
}
